import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import { getSongDetail, getSongLyric } from "@/views/player/service/player";
import { IRootState } from "@/store";
import { parseLyric } from "@/utils/parse-lyric";

interface IThunkState {
  state: IRootState;
}

interface IPlayerState {
  currentSong: any;
  lyrics: any[];
  lyricIndex: number;
  playSongList: any[];
  playSongIndex: number;
  playMode: number;
}

const initialState: IPlayerState = {
  currentSong: {},
  lyrics: [],
  lyricIndex: -1,
  playSongList: [
    {
      name: "起风了",
      id: 1330348068,
      pst: 0,
      t: 0,
      ar: [
        {
          id: 12085562,
          name: "买辣椒也用券",
          tns: [],
          alias: []
        }
      ],
      alia: ["原曲：《ヤキモチ》—高桥优"],
      pop: 100,
      st: 0,
      rt: "",
      fee: 8,
      v: 43,
      crbt: null,
      cf: "",
      al: {
        id: 74715426,
        name: "起风了",
        picUrl:
          "https://p1.music.126.net/diGAyEmpymX8G7JcnElncQ==/109951163699673355.jpg",
        tns: [],
        pic_str: "109951163699673355",
        pic: 109951163699673360
      },
      dt: 325868,
      h: {
        br: 320000,
        fid: 0,
        size: 13037236,
        vd: -77525,
        sr: 44100
      },
      m: {
        br: 192000,
        fid: 0,
        size: 7822359,
        vd: -74987,
        sr: 44100
      },
      l: {
        br: 128000,
        fid: 0,
        size: 5214920,
        vd: -73504,
        sr: 44100
      },
      sq: {
        br: 985873,
        fid: 0,
        size: 40158105,
        vd: -77508,
        sr: 44100
      },
      hr: {
        br: 2832349,
        fid: 0,
        size: 115371553,
        vd: -77476,
        sr: 88200
      },
      a: null,
      cd: "1",
      no: 1,
      rtUrl: null,
      ftype: 0,
      rtUrls: [],
      djId: 0,
      copyright: 0,
      s_id: 0,
      mark: 536879104,
      originCoverType: 1,
      originSongSimpleData: null,
      tagPicList: null,
      resourceState: true,
      version: 43,
      songJumpInfo: null,
      entertainmentTags: null,
      awardTags: null,
      single: 0,
      noCopyrightRcmd: null,
      cp: 1415923,
      rtype: 0,
      rurl: null,
      mst: 9,
      mv: 10782615,
      publishTime: 1543766400000
    },
    {
      name: "把回忆拼好给你",
      id: 1403318151,
      pst: 0,
      t: 0,
      ar: [
        {
          id: 14312549,
          name: "王贰浪",
          tns: [],
          alias: []
        }
      ],
      alia: [],
      pop: 100,
      st: 0,
      rt: "",
      fee: 8,
      v: 18,
      crbt: null,
      cf: "",
      al: {
        id: 83305009,
        name: "把回忆拼好给你",
        picUrl:
          "https://p2.music.126.net/CBx2K_jEN3SNWwYztagPPw==/109951164485969446.jpg",
        tns: [],
        pic_str: "109951164485969446",
        pic: 109951164485969440
      },
      dt: 381000,
      h: {
        br: 320001,
        fid: 0,
        size: 15243015,
        vd: -41846,
        sr: 44100
      },
      m: {
        br: 192001,
        fid: 0,
        size: 9145826,
        vd: -39239,
        sr: 44100
      },
      l: {
        br: 128001,
        fid: 0,
        size: 6097232,
        vd: -37537,
        sr: 44100
      },
      sq: {
        br: 885198,
        fid: 0,
        size: 42157601,
        vd: -41890,
        sr: 44100
      },
      hr: null,
      a: null,
      cd: "01",
      no: 1,
      rtUrl: null,
      ftype: 0,
      rtUrls: [],
      djId: 0,
      copyright: 0,
      s_id: 0,
      mark: 0,
      originCoverType: 1,
      originSongSimpleData: null,
      tagPicList: null,
      resourceState: true,
      version: 18,
      songJumpInfo: null,
      entertainmentTags: null,
      awardTags: null,
      single: 0,
      noCopyrightRcmd: null,
      rtype: 0,
      rurl: null,
      mst: 9,
      cp: 0,
      mv: 0,
      publishTime: 1573660800000
    }
  ],
  playSongIndex: -1,
  playMode: 0 // 0: 顺序， 1: 随机, 2：单曲循环
};

const playerSlice = createSlice({
  name: "player",
  initialState,
  reducers: {
    changeCurrentSongAction(state, action) {
      state.currentSong = action.payload;
    },
    changeLyricsAction(state, action) {
      state.lyrics = action.payload;
    },
    changeLyricIndexAction(state, { payload }) {
      state.lyricIndex = payload;
    },
    changePlaySongIndexAction(state, { payload }) {
      state.playSongIndex = payload;
    },
    changePlaySongListAction(state, { payload }) {
      state.playSongList = payload;
    },
    changePlayModeAction(state, { payload }) {
      state.playMode = payload;
    }
  }
});

export const fetchCurrentSongAction = createAsyncThunk<
  void,
  number,
  IThunkState
>("currentSong", (id: number, { dispatch, getState }) => {
  // 1. 准备播放某一首歌曲时，分成两种情况
  const playSongList = getState().player.playSongList;
  const findIndex = playSongList.findIndex((item) => item.id === id);
  // 没有在列表找到相同的歌曲
  if (findIndex === -1) {
    console.log("没有在列表中找到相同的歌曲");
    // 1. 获取歌曲信息
    getSongDetail(id).then((res) => {
      // 1. 获取song
      if (!res.songs.length) return;
      const song = res.songs[0];
      // 2. 将 song 放到 currentSong 中
      const newPlaySongList = [...playSongList];
      newPlaySongList.push(song);
      dispatch(changeCurrentSongAction(song));
      dispatch(changePlaySongListAction(newPlaySongList));
      dispatch(changePlaySongIndexAction(newPlaySongList.length - 1));
    });
  } else {
    console.log("在列表中找到相同的歌曲");
    // 有相同的
    const song = playSongList[findIndex];
    dispatch(changeCurrentSongAction(song));
    dispatch(changePlaySongIndexAction(findIndex));
  }

  // 2. 获取歌词数据
  getSongLyric(id).then((res) => {
    // 1. 获取歌词
    const lyricString = res.lrc.lyric;
    // 2. 对歌词进行解析
    const lyrics = parseLyric(lyricString);
    // 3. 将歌词放进 state
    dispatch(changeLyricsAction(lyrics));
  });
});

export const changeMusicAction = createAsyncThunk<void, boolean, IThunkState>(
  "changemusic",
  (isNext, { dispatch, getState }) => {
    // 1. 获取 state 中的数据
    const player = getState().player;
    const playMode = player.playMode;
    const songIndex = player.playSongIndex;
    const songList = player.playSongList;
    // 2. 根据不同模式计算不同的下一首歌曲的索引
    let newIndex = songIndex;

    if (playMode === 1) {
      // 随机播放
      newIndex = Math.floor(Math.random() * songList.length);
    } else {
      // 单曲循环 和 顺序播放
      newIndex = isNext ? songIndex + 1 : songIndex - 1;
      if (newIndex > songList.length - 1) newIndex = 0;
      if (newIndex < 0) newIndex = songList.length - 1;
    }
    // 3. 获取当前歌曲
    const song = songList[newIndex];
    dispatch(changeCurrentSongAction(song));
    dispatch(changePlaySongIndexAction(newIndex));

    getSongLyric(song.id).then((res) => {
      // 1. 获取歌词字符串
      const lyricString = res.lrc.lyric;
      // 2. 对歌词进行解析
      const lyrics = parseLyric(lyricString);
      // 3. 放到 store 中
      dispatch(changeLyricsAction(lyrics));
    });
  }
);

export const {
  changeCurrentSongAction,
  changeLyricsAction,
  changeLyricIndexAction,
  changePlaySongIndexAction,
  changePlaySongListAction,
  changePlayModeAction
} = playerSlice.actions;

export default playerSlice.reducer;
